/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.manager;

import entity.Era;
import entity.Player;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import util.Digest;

/**
 *
 * @author antonio
 */
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Stateless
public class PlayerManagerBean implements PlayerManagerBeanLocal {

    @PersistenceContext(unitName = "BrowserGame-ejbPU")
    private EntityManager entityManager;
    @Resource(name = "messageDigestAlgorithm")
    private String messageDigestAlgorithm;

    @Override
    public boolean initPlayer(String username, String password, String email) {
        if (entityManager.find(Player.class, username) != null) {
            return false;
        }
        Player player = new Player();
        player.setUsername(username);
        String hashPsw = null;
        try {
            hashPsw = Digest.digest(password, this.messageDigestAlgorithm);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PlayerManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(PlayerManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        player.setPassword(hashPsw);
        player.setEmail(email);
        Era era = entityManager.find(Era.class, 1);
        player.setEra(era);
        entityManager.persist(player);
        return true;
    }

    @Override
    public Player find(String username) {
        return entityManager.find(Player.class, username);
    }

    @Override
    public void edit(Player player) {
        entityManager.merge(player);
    }
}
